<template>
	<div>
		<div ref="editorRef"></div>
		<a-drawer :class="classes.reviewDraw" :footer="false" :width="320" :title="`评论${reviewList.length}`" :visible="reviewModal" :mask="false" @cancel="closeReview" unmountOnClose>
			<a-scrollbar :style="scrollbarStyle">
				<div :style="{ height: curReview?.y - 80 + 'px' }"></div>
				<div :class="classes.reviewWrap">
					<div :class="classes.reviewItem">
						<div :class="classes.mark">{{ curReview?.text }}</div>
						<div :class="classes.my">
							<div :class="classes.sendWrap">
								<a-input-search v-model="reviewText" placeholder="输入评论" button-text="发送" :max-length="50" show-word-limit search-button @search="handleAddReview" />
							</div>
						</div>
					</div>
					<div :class="classes.reviewItem" v-for="(v, i) in reviewList" :key="i">
						<div :class="classes.mark">{{ v.refText }}</div>
						<div :class="classes.my">
							<div :class="classes.avatar">
								<img :src="v.avatar || 'http://doc.turntip.cn/uploads/busy-server/avatar_1930c17f144.png'" alt="" />
								<span> {{ v.name || "游客" + i }}</span>
								<span :class="classes.time"> {{ formatDate(v.ct) }}</span>
							</div>
							<div :class="classes.replay">{{ v.text }}</div>
						</div>
					</div>
				</div>
			</a-scrollbar>
		</a-drawer>
	</div>
</template>

<script setup lang="ts">
import EditorJS from "@editorjs/editorjs"
import Header from "./components/MyHeader"
import ImageTool from "./components/MyImageTool"
import LinkTool from "@editorjs/link"
import Alert from "editorjs-alert"
import NestedList from "@editorjs/nested-list"
import Checklist from "@editorjs/checklist"
import InlineCode from "@editorjs/inline-code"
import Strikethrough from "@sotaproject/strikethrough"
import TextVariantTune from "@editorjs/text-variant-tune"
import Align from "editorjs-text-alignment-blocktune"
import IndentTune from "editorjs-indent-tune"
import Quote from "./components/Quote"
import MyInlineLink from "./components/MyInlineLink"
import Swiper from "./components/Swiper"
import AiWrite from "./components/AiWrite"
import Form from "./components/Form"
// import Ocr from "./components/Ocr"
import InfoCard from "./components/InfoCard"
import Board from "./components/Board"
import Sheet from "./components/Sheet"
import PageLine from "./components/PageLine"
import Undo from "editorjs-undo"
import { MDImporter, MDParser } from "@/components/tMd"
import MyTable from "./components/MyTable"
import CodeBox from "./components/MyCodeBox"
import Math from "./components/Math"
import Video from "./components/Video"
import Audio from "./components/Audio"
import PDFParser from "./components/PDFParser"
import PDFTextParser from "./components/PDFTextParser"
import DocParser from "./components/DocParser"
import Mind from "./components/Mind"
import CopyBlockTune from "./components/CopyBlockTune"
import Iframe from "./components/Iframe"
import Divider from "./components/Divider"
import MyMark from "./components/MyMark"
import MyColor from "./components/MyColor"
import Paragraph from "./components/Paragraph"
import MyPaper from "./components/MyPaper"
import MyLineView from "./components/MyLineView"
import Underline from "./components/Underline"
import Chart from "./components/Chart"
import InlineMathTool from "./components/InlineMathTool"
import ProMind from "./components/ProMind"
import FontSize from "./components/FontSize"
import DragDrop from "editorjs-drag-drop"
import Attachment from "./components/Attachment/"
import i18n from "./i18n"
import { uploadFn } from "@/utils/file"
import { getWordReview, addWordReview } from "./api"
import mittBus from "@/utils/mitt"
import { formatDate } from "xijs"
import "katex/dist/katex.min.css"
import classes from "./index.module.less"
import { getSearchParams } from "@/utils"

interface Props {
	readOnly?: boolean
	minHeight: number
}

const props = defineProps<Props>()
const emits = defineEmits(["getEditorInstance", "handleEditorChange"])
const editorRef = ref()
const BASE_API_URL = '/api'
const reviewModal = ref<boolean>(false)
let curReview = reactive<any>({})
const reviewList = ref<any[]>([])
const reviewText = ref<string>("")
const params = getSearchParams()
const scrollbarStyle = reactive({
	width: "272px",
	height: window.innerHeight - 120 + "px",
})

watch(
	() => params,
	(val) => {
		handlegGetWordReview()
	},
	{ deep: true }
)
mittBus.on("addReview", (val) => {
	openReview(val)
})
const closeReview = () => {
	reviewModal.value = false
}
const openReview = (row: any) => {
	reviewModal.value = true
	const markEl = document.querySelector(`#${row.id}`)
	const rect = markEl?.getBoundingClientRect()
	curReview = { ...row, y: rect?.top }
	fetchReviewList(row.id)
}
const fetchReviewList = (id: string) => {
	// const params = getSearchParams();
	const result = getWordReview(undefined, id)
	reviewList.value = result
	handlegGetWordReview()
}
const handleAddReview = (text: string) => {
	// const params = getSearchParams();
	addWordReview(undefined, {
		mid: curReview.id,
		text,
		refText: curReview.text,
	})
	reviewText.value = ""
	fetchReviewList(curReview.id)
}
// 删除评论(待规划)
const handleDelMark = (row: any) => {
	console.log(row)
}
// 获取评论列表
const handlegGetWordReview = () => {
	setTimeout(() => {
		const list = getWordReview()
		const markListMap: any = {}
		list.forEach((v: any) => {
			if (!markListMap[v.mid]) {
				markListMap[v.mid] = {
					id: v.mid,
					count: 1,
				}
			} else {
				markListMap[v.mid].count = markListMap[v.mid].count + 1
			}
		})
		let markList = Object.values(markListMap)
		// let contentW = editorRef.current?.offsetWidth;
		// // 获取容器到窗口的可视距离
		// let contentX = editorRef.current?.getBoundingClientRect().left;
		markList.forEach((v: any) => {
			let marks = document.querySelectorAll(`.${v.id}`)
			let mark = marks[marks.length - 1]
			// const tip = make('span', [styles.noteTip, 'fm-note'], { innerHTML: v.count });
			// // 计算tip如果在整个文档右侧, 需要移动的距离
			// const offsetLeft = mark?.getBoundingClientRect().left;
			// const left = contentW - offsetLeft + contentX + tip.offsetWidth + 10;
			// tip.style.left = `${left}px`;
			// tip.contentEditable = 'false';
			// mark?.append(tip);
			// 给每个元素添加事件, 以便能打开评论弹窗
			mark?.addEventListener(
				"click",
				(e) => {
					e.stopPropagation()
					const id = mark.id
					const text = mark.textContent
					mittBus.emit("addReview", { id, text })
				},
				false
			)
		})
	}, 600)
}
const init = () => {
	nextTick(() => {
		const editor: any = new EditorJS({
			onReady: () => {
				const undoObj = new Undo({ editor, maxLength: 50 })
				// 保证组件之间的拖拽
				new DragDrop(editor)
				editor.record = undoObj
				emits("getEditorInstance", editor)
			},
			readOnly: props.readOnly,
			// 编辑器change回调
			onChange: (api, event) => {
				emits("handleEditorChange", api, event)
			},
			data: JSON.parse(localStorage.getItem("data") || "{}"),
			holder: editorRef.value,
			autofocus: true,
			minHeight: props.minHeight,
			// 工具集
			tools: {
				// 标题
				header: {
					class: Header as any,
					inlineToolbar: true,
					config: {
						placeholder: "请输入标题",
					},
				},
				// 图片
				image: {
					class: ImageTool as any,
					config: {
						uploader: {
							/**
							 * Upload file to the server and return an uploaded image data
							 * @param {File} file - file selected from the device or pasted by drag-n-drop
							 * @return {Promise.<{success, file: {url}}>}
							 */
							async uploadByFile(file: File) {
								// your own uploading logic here
								const data = await uploadFn(file)
								return {
									success: 1,
									file: {
										...data,
										// any other image data you want to store, such as width, height, color, extension, etc
									},
								}
							},
						},
					},
				},
				// 链接
				link: {
					class: LinkTool as any,
					config: {
						endpoint: `${BASE_API_URL}/fetchUrl`,
						headers: {
							// credentials: 'include',
						},
					},
				},
				// 引用
				quote: {
					class: Quote as any,
					inlineToolbar: true,
					shortcut: "CMD+SHIFT+O",
					config: {
						quotePlaceholder: "输入引用",
						captionPlaceholder: "引用作者",
					},
				},
				// 文本选中添加链接
				MyInlineLink: MyInlineLink,
				// 调整字体
				fontSize: FontSize,
				// 轮播图
				swiper: Swiper,
				// pro 思维导图
				proMind: ProMind,
				// AI
				aiWrite: {
					class: AiWrite as any,
					config: {
						placeholder: "向AI发送你的需求~",
					},
				},
				// 表单
				form: Form,
				// ocr图像识别
				// Ocr: Ocr,
				// 信息流卡片
				infoCard: InfoCard,
				// 创意白板
				board: Board,
				// 分页
				pageLine: PageLine,
				chart: {
					class: Chart,
				},
				// 警告
				alert: {
					class: Alert,
					inlineToolbar: true,
					shortcut: "CMD+SHIFT+A",
					config: {
						defaultType: "primary",
						messagePlaceholder: "输入内容",
					},
				},
				// 列表
				list: {
					class: NestedList as any,
					inlineToolbar: true,
					config: {
						defaultStyle: "unordered",
					},
				},
				// 任务清单
				checklist: {
					class: Checklist,
					inlineToolbar: true,
				},
				// 表格
				table: {
					class: MyTable as any,
					inlineToolbar: true,
					config: {
						rows: 2,
						cols: 3,
					},
				},
				// 代码块
				codeBox: {
					class: CodeBox,
					config: {
						themeName: "an-old-hope", // Optional
						useDefaultTheme: "dark", // Optional. This also determines the background color of the language select drop-down
					},
				},
				// 数学公式
				math: {
					class: Math as any,
					config: {
						default: "x=y",
					},
				},
				// 附件
				attachment: {
					class: Attachment as any,
					config: {
						data: {},
					},
				},
				video: {
					class: Video as any,
					config: {
						placeholder: "请输入视频地址或者第三方iframe",
						// <iframe src="//player.bilibili.com/player.html?aid=1201001117&bvid=BV1uF4m1j7NY&cid=1453275883&p=1" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"> </iframe>
					},
				},
				audio: {
					class: Audio as any,
					config: {
						placeholder: "请输入音频地址",
					},
				},
				// pdf内嵌
				PDFParser: {
					class: PDFParser as any,
					config: {
						placeholder: "请输入PDF地址",
					},
				},
				// PDF解析
				PDFTextParser: {
					class: PDFTextParser as any,
				},
				// Word 解析
				DocParser: {
					class: DocParser as any,
					config: {
						data: {},
					},
				},
				// 电子表格
				sheet: Sheet,
				mind: Mind,
				iframe: {
					class: Iframe as any,
					config: {
						placeholder: "请输入iframe地址",
					},
				},
				// 分割线
				divider: Divider,
				// 文本选中标记
				Marker: {
					class: MyMark,
					shortcut: "CMD+SHIFT+M",
				},
				MyColor: MyColor,
				Paper: {
					class: MyPaper,
				},
				inlineCode: {
					class: InlineCode,
					shortcut: "CMD+SHIFT+M",
				},
				inlineMath: {
					class: InlineMathTool,
					inlineToolbar: true,
				},
				underline: Underline,
				textVariant: TextVariantTune,
				// 应用到段落的tunes
				paragraph: {
					class: Paragraph as any,
					tunes: ["indentTune", "textVariant", "anyTuneName", "copyBlockTune"],
				},
				anyTuneName: {
					class: Align,
					config: {
						default: "left",
					},
				},
				// 内联删除线
				strikethrough: Strikethrough,
				indentTune: IndentTune as any,
				MyLineView: {
					class: MyLineView as any,
				},
				markdownParser: MDParser,
				copyBlockTune: CopyBlockTune as any,
				mardkownImporter: MDImporter,
			},
			tunes: ["indentTune", "copyBlockTune"],
			// 国际化
			i18n,
		})
		handlegGetWordReview()
	})
}
init()
</script>

<style scoped></style>

